/*
Copyright 2010,2011 Matt Van Der Westhuizen

This file is part of CGLL.

CGLL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Jumpers is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with CGLL.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.chaoticengine.cgll.factory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.newdawn.slick.util.ResourceLoader;

/**
 *
 * @author Matt Van Der Westhuizen <mattpwest@gmail.com>
 */
public abstract class AbstractFactory {
    protected HashMap<String, ByteArrayOutputStream> cache = new HashMap<String, ByteArrayOutputStream>();

    protected InputStream getCachedResource(String filename) {
        InputStream is = null;
        if (!cache.containsKey(filename)) {
            ByteArrayOutputStream bos = null;
            is = ResourceLoader.getResourceAsStream(filename);

            try {
                bos = new ByteArrayOutputStream(is.available());
                int b = is.read();
                while (b >= 0) {
                    bos.write(b);

                    b = is.read();
                }

                is.close();
                bos.close();
            } catch (IOException ioEx) {
                System.out.println("Error: Failed to cache bullet definition file '" + filename + "'.");
                ioEx.printStackTrace();
                System.exit(-1);
            }

            cache.put(filename, bos);
        }

        is = new ByteArrayInputStream(cache.get(filename).toByteArray());

        return(is);
    }

    public List<String> getAvailable() {
        ArrayList<String> result = new ArrayList<String>();
        for (String filename : cache.keySet()) {
            File f = new File(filename);
            String name = stripExtension(f.getName());
            result.add(name);
        }

        return(result);
    }

    private String stripExtension(String filename) {
        int indx = filename.lastIndexOf(".");
        if (indx > 0) {
            return(filename.substring(0, indx));
        } else {
            return(filename);
        }
    }
}
